<?php
/**
 * Created by PhpStorm OF yuyi.
 * User: YUYI
 * Date: 2018/6/7 0007
 * Time: 上午 9:21
 * Administrator
 */

namespace app\common\util;


trait PostUtil
{
    /**
     * 使用get访问
     */
    public static function getVisit($url,$data,$timeout = 30)
    {
        if (is_array($data)){
            $gData = http_build_query($data);
        }elseif(is_string($data)){
            $gData = $data;
        }
        $opts = ['http'=>
            [
                'method'=>"GET",
                'timeout'=>$timeout,
            ]
        ];
        $context = stream_context_create($opts);
        $html =file_get_contents($url.$gData, false, $context);
        return $html;
    }

    /**
     * 使用post访问
     */
    public static function postVisit($url,$data)
    {
            $postdata = http_build_query(
                $data
            );

            $opts = array('http' =>
                array(
                    'method' => 'POST',
                    'header' => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $postdata
                )
            );
            $context = stream_context_create($opts);
            $result = file_get_contents($url, false, $context);
            return $result;
    }

    /**
     * curl post访问url
     * @param $url string 访问路径
     * @param $post_data array|string 请求数据
     * @param array $header
     * @param int $timeout
     * @return mixed
     */
    public static function postCurlVisit($url,$post_data,$header = [],$timeout = 30)
    {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        if (is_array($post_data)){
            $pdata = http_build_query ( $post_data );
            if($pdata != ''){
                curl_setopt($ch, CURLOPT_POSTFIELDS, $pdata);
            }
        }else{
            curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
        }
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if ($header)
            curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt($ch, CURLOPT_HEADER, false);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        return $file_contents;
    }
}